package com.example.htmlfx.utils;

import com.example.htmlfx.entity.ParsingResultEntity;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 数据保存
 *
 * @author gzkemays
 * @date 2021/8/4
 */
public class DataSaveUtils {
  /**
   * 下载文件
   *
   * @param path 用户选中的文件夹位置
   * @param url 文件地址
   * @throws IOException IO 读取失败
   */
  public static void downloadFiles(String path, String url) throws IOException {
    String imageName = path + File.separator + url.substring(url.lastIndexOf("/") + 1);
    if (url.startsWith("http")) {
      URL uri = new URL(url);
      DataInputStream dis = new DataInputStream(uri.openStream());
      FileOutputStream fos = new FileOutputStream(new File(imageName));
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      byte[] buffer = new byte[1024];
      int length;
      while ((length = dis.read(buffer)) != -1) {
        baos.write(buffer, 0, length);
      }
      fos.write(baos.toByteArray());
      dis.close();
      fos.close();
    }
  }

  public static void downloadFilesToZip(String path, List<ParsingResultEntity> list)
      throws IOException {
    List<ParsingResultEntity> lists =
        list.stream().filter(item -> item.getUrl().startsWith("http")).collect(Collectors.toList());
    File file = new File(path + File.separator + "解析打包图集 - " + System.nanoTime() + ".zip");
    file.createNewFile();
    System.out.println("list = " + lists);
    if (!lists.isEmpty()) {
      try (FileOutputStream fos = new FileOutputStream(file);
          ZipOutputStream zos = new ZipOutputStream(fos)) {
        int i = 0;
        while (i < lists.size()) {
          String urlStr = lists.get(i).getUrl();
          URL url = new URL(urlStr);
          // 加入 zip
          zos.putNextEntry(new ZipEntry(urlStr.substring(urlStr.lastIndexOf("/") + 1)));
          try {
            URLConnection urlConnection = url.openConnection();
            urlConnection.setConnectTimeout(30000);
            urlConnection.setReadTimeout(30000);
            InputStream is = urlConnection.getInputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) != -1) {
              zos.write(buffer, 0, length);
            }
            i++;
            zos.flush();
            fos.flush();
          } catch (FileNotFoundException ex) {
            i++;
          }
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}
